import 'package:flustars/flustars.dart';
import 'package:flutter/material.dart';
import 'package:yuan_hang_app/base/full_base_page.dart';
import 'package:yuan_hang_app/res/w_colors.dart';
import 'package:yuan_hang_app/res/w_dimens.dart';
import 'package:yuan_hang_app/utils/common_utils.dart';
import 'package:yuan_hang_app/utils/size_utils.dart';
import 'package:yuan_hang_app/utils/string_utils.dart';
import 'package:yuan_hang_app/utils/common_req_utils.dart';
import 'package:yuan_hang_app/views/home/view/drive/drive_registration_page.dart';
import 'package:yuan_hang_app/views/home/view/order/order_model.dart';
import 'package:yuan_hang_app/widget/status_btn.dart';
import 'package:yuan_hang_app/widget/w_line.dart';
import 'package:yuan_hang_app/widget/w_text.dart';
import '../../../../base/base_state.dart';
import '../../../../http/api.dart';
import '../../../../http/http_utils.dart';
import '../../../../res/w_constant.dart';
import '../../../../utils/router_helper.dart';
import '../../../../widget/custom_search.dart';
import '../../../../widget/sort_content.dart';
import '../../../../widget/tab_btn.dart';
import '../../../../widget/w_list_view.dart';
import '../../../../widget/w_popup_window.dart';
import '../../../../widget/w_toast.dart';
import '../../model/book_manage_model.dart';
import '../../model/drive_consts.dart';
import 'book_add_page.dart';
import 'book_cancel_page.dart';
import 'book_detail_page.dart';
import 'book_update_page.dart';

class BookManagePage extends StatefulWidget {
  final String? phone;

  const BookManagePage({super.key, this.phone});

  @override
  BaseState<BookManagePage> createState() => _BookManagePageState();
}

class _BookManagePageState extends BaseState<BookManagePage> {
  int selectedIndex = 0; // 当前选中的标签索引，初始为全部
  int dateIndex = 0; //日期时间检索下标
  List<Map> saleManList = WConstant().salesmanList;

  List bookList = [];
  List<Map> tabList1 = [
    {"title": "全部"},
    {"title": "今日"},
    {"title": "明日"},
    {"title": "将来"}
  ];
  List<Map> tabList2 =
      CommonReqUtils.getLabelListByKey(CommonReqUtils.bookStatus);

  List currentDriveList = [];

  String autoPhone = "";

  //已预约、签约中、待开始、试驾中、已结束、已取消

  Map sortParams = {};

  var mCurrentStatus;
  int mPage = 0;
  String keyword = "";

  @override
  void initState() {
    if (widget.phone != null) {
      keyword = widget.phone!;
      autoPhone = widget.phone!;
    }
    super.initState();
    tabList2.insert(0, {"value": "0", "label": "全部"});
  }

  @override
  FullBasePage buildState(BuildContext context) {
    return FullBasePage(
        title: "预约列表",
        child: Column(
          children: <Widget>[
            // 文字标签按钮
            CustomSearch(
              hintText: "客户名称/手机号",
              initText: autoPhone,
              showSort: true,
              onSortClick: () {
                WPopupWindow.showSort(
                    context: context,
                    sortType: SortType.BOOKING,
                    sortParams: sortParams,
                    isScrollControlled: false,
                    onSelected: (params) {
                      sortParams = params;
                      showLoading();
                      fetchDataList();
                    });
              },
              onTextChange: (text) {
                keyword = text;
                mPage = 1;
                showLoading();
                CommonUtils.antiShake(fetchDataList);
              },
            ),
            TabBtn(
              paddingTop: 5.px,
              tabList: tabList1,
              tabClick: (index) {
                setState(() {
                  dateIndex = index;
                  mPage = 1;
                  showLoading();
                  fetchDataList();
                });
              },
            ),
            TabBtn(
              tabList: tabList2,
              titleKey: "label",
              tabClick: (index) {
                setState(() {
                  mPage = 1;
                  selectedIndex = index;
                  showLoading();
                  fetchDataList();
                });
              },
            ),
            Expanded(
              child: WListView(
                  padding: EdgeInsets.only(top: 5.px),
                  itemBuilder: _noticeMsgItem,
                  getDataList: (currentState, page) {
                    mCurrentStatus = currentState;
                    mPage = page;
                    fetchDataList();
                  }),
            ),
            GestureDetector(
              onTap: () {
                RouteHelper.pushWidget(context, const BookAddPage())
                    .then((res) {
                  if (res != null && res) {
                    mPage = 1;
                    showLoading();
                    fetchDataList();
                  }
                });
              },
              child: Container(
                margin:
                    EdgeInsets.symmetric(vertical: 16.px, horizontal: 10.px),
                width: SizeUtils.screenW() - 48.px,
                alignment: Alignment.center,
                height: 48.px,
                decoration: BoxDecoration(
                  color: WColors.primaryColor,
                  borderRadius: BorderRadius.circular(24.px),
                ),
                child: WText(
                  "新增",
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: WDimens.tsXLarge,
                  ),
                ),
              ),
            )
          ],
        ));
  }

  void fetchDataList() {
    DateTime now = DateTime.now();
    Map<String, dynamic> params = {
      "pageNum": mPage,
      "limit": 20,
      "queryParam": keyword,
      "appointType": StringUtils.safeGetValue(sortParams["appointType"]) ?? "",
      "createdAtBegin": StringUtils.safeGetValue(
              sortParams["createdAtBegin"] == null
                  ? ""
                  : sortParams["createdAtBegin"] + " 00:00:00") ??
          "",
      "createdAtEnd": StringUtils.safeGetValue(
              sortParams["createdAtEnd"] == null
                  ? ""
                  : sortParams["createdAtEnd"] + " 00:00:00") ??
          "",
      "appointDateBegin": "",
      "appointDateEnd": "",
      "appointStatus":
          selectedIndex == 0 ? "" : tabList2[selectedIndex]["value"],
      "today": dateIndex == 1
          ? DateUtil.formatDate(now, format: DateFormats.y_mo_d)
          : "",
      "tomorrow": dateIndex == 2
          ? DateUtil.formatDate(DateTime(now.year, now.month, now.day + 1),
              format: DateFormats.y_mo_d)
          : "",
      "later": dateIndex == 3
          ? DateUtil.formatDate(DateTime(now.year, now.month, now.day + 2),
              format: DateFormats.y_mo_d)
          : ""
    };
    HttpUtils().post(Api.getTestDriveBookingList, data: params).then((value) {
      hideLoading();
      if (value.resultCode == 200) {
        List list = value.data == null ? [] : value.data["records"];


        mCurrentStatus.onRefreshData(list, mPage);
        if (mPage == 1) {
          bookList.clear();
        }
        bookList.addAll(list);
        tabList1[1]["count"] = list[0]["todayNum"];
        tabList1[2]["count"] = list[0]["tomorrowNum"];
        tabList1[3]["count"] = list[0]["lateNum"];
        setState(() {});
      } else {
        mCurrentStatus?.onFail(value.errMsg);
      }
    }).catchError((e) {
      hideLoading();
    });
  }

  Widget _noticeMsgItem(context, index, currentDriveList) {
    Map item = currentDriveList[index];
    Map statusInfo = BookManageModel.exchangeStatus(
        CommonReqUtils.exchangeCodeToName(
            CommonReqUtils.bookStatus, item["appointStatus"]));
    String model = CommonReqUtils.exchangeCodeToName(
        CommonReqUtils.carType, item["modelId"]);
    return GestureDetector(
        onTap: () {
          RouteHelper.pushWidget(
              context,
              BookDetailPage(
                bookId: item["id"],
                cancelPerson: item["cancelPerson"] ?? "",
                saleMan: item["saleMan"] ?? "",
              ));
        },
        child: Container(
            alignment: Alignment.center,
            margin: EdgeInsets.only(left: 10.px, right: 10.px, bottom: 5.px),
            padding: EdgeInsets.only(right: 10.px),
            decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(10.px),
                color: Colors.white,
                boxShadow: const [
                  BoxShadow(
                      //线框阴影线条
                      color: WColors.border,
                      offset: Offset(0, 1),
                      blurRadius: 2)
                ]),
            child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  SizedBox(height: 5.px),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      WLine(
                        height: 16.px,
                        width: 4.px,
                        color: WColors.primaryColor,
                        marginRight: 10.px,
                      ),
                      Expanded(
                          child: Row(
                        children: [
                          Flexible(
                            flex: 1,
                            child: WText(
                              item["customerName"],
                              overflow: TextOverflow.ellipsis,
                              style: TextStyle(
                                  fontSize: WDimens.tsLarge,
                                  color: WColors.mainTextColor,
                                  fontWeight: FontWeight.bold),
                            ),
                          ),
                        ],
                      )),
                      StatusBtn(
                        width: 68.px,
                        height: 28.px,
                        color: statusInfo["color"],
                        text: CommonReqUtils.exchangeCodeToName(
                            CommonReqUtils.bookStatus, item["appointStatus"]),
                        isItemBtn: true,
                        isTag: true,
                      ),
                    ],
                  ),
                  WLine(
                    height: 1.px,
                    marginBottom: 5.px,
                    marginTop: 5.px,
                  ),
                  ItemSingleInfoRow(
                      StringUtils.safeGetValue(item["phone"], placeHolder: '-')),
                  ItemInfoRow(
                      CommonReqUtils.exchangeCodeToName(
                          CommonReqUtils.appointType, item["appointType"]),
                      StringUtils.safeGetValue(model, placeHolder: '-')),
                  ItemSingleInfoRow(StringUtils.safeGetValue(
                      StringUtils.safeGetValue(item["saleMan"]),
                      placeHolder: "-")),
                  Padding(
                    padding: EdgeInsets.only(left: 10.px),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        WText(
                          "预约时间：${item["appointTime"]}",
                          style: TextStyle(
                              color: WColors.hintTextColor,
                              fontSize: WDimens.tsMedium),
                        ),
                        //只有已取消状态下才会有取消时间
                        Offstage(
                          offstage: (CommonReqUtils.exchangeCodeToName(
                                  CommonReqUtils.bookStatus,
                                  item["appointStatus"]) !=
                              "已取消"),
                          child: WText(
                            "取消时间：${item["cancelTime"]}",
                            style: TextStyle(
                                color: WColors.hintTextColor,
                                fontSize: WDimens.tsMedium),
                          ),
                        ),
                      ],
                    ),
                  ),
                  Offstage(
                    offstage: statusInfo["pressText"] == "" &&
                        statusInfo["openFlag"] == false,
                    child: WLine(
                      marginTop: 5.px,
                      height: 0.5.px,
                    ),
                  ),
                  Padding(
                    padding: EdgeInsets.symmetric(vertical: 5.px),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.end,
                      children: [
                        Offstage(
                          offstage: item["appointType"] == 10221001 ||
                              item["appointStatus"] != 10211001,
                          child: StatusBtn(
                            height: 28.px,
                            width: 68.px,
                            color: WColors.redMain,
                            text: "试驾",
                            isItemBtn: true,
                            onPressed: () {
                             var bookSource= item["driveSource"]!=null?(int.parse(item["driveSource"])==10091017?24711002:24711004):"";
                              RouteHelper.pushWidget(
                                  context,
                                  DriveRegistrationPage(
                                    bookInfo: {
                                      "id": item["id"],
                                      "customerName": item["customerName"],
                                      "phone": item["noPhone"],
                                      "modelId": item["modelId"],
                                      "driveSource": bookSource,
                                    },
                                  ));
                            },
                          ),
                        ),
                        Offstage(
                          offstage: statusInfo["pressText"] == "",
                          child: StatusBtn(
                            margin: EdgeInsets.only(left: 10.px),
                            height: 28.px,
                            width: 68.px,
                            color: WColors.green,
                            text: statusInfo["pressText"],
                            isItemBtn: true,
                            onPressed: () {
                              switch (statusInfo["pressText"].toString()) {
                                case "确认":
                                  //发起http请求
                                  showLoading();
                                  Map<String, dynamic> dataMap = {
                                    "id": item["id"]
                                  };
                                  HttpUtils()
                                      .post(Api.confirmTestBookInfo,
                                          data: dataMap)
                                      .then((data) {
                                    hideLoading();
                                    if (data.resultCode == 200) {
                                      Toast.toast("预约确认成功");
                                      bookList[index]["appointStatus"] =
                                          10211002;
                                      setState(() {});
                                    } else {
                                      Toast.toast(data.errMsg ?? "");
                                    }
                                  });
                                default:
                                  // 可选：处理未知状态
                                  print("未知操作");
                              }
                            },
                          ),
                        ),
                        Offstage(
                          offstage: statusInfo["pressText"] == "",
                          child: StatusBtn(
                            margin: EdgeInsets.only(left: 10.px),
                            height: 28.px,
                            width: 68.px,
                            color: WColors.primaryColor,
                            text: "修改",
                            isItemBtn: true,
                            onPressed: () {
                              RouteHelper.pushWidget(
                                      context,
                                      BookUpdatePage(
                                          bookId: item["id"],
                                          saleMan: item["saleMan"] ?? ""))
                                  .then((res) {
                                //    print("点击了修改============$res");
                                if (res != null && res) {
                                  mPage = 1;
                                  showLoading();
                                  fetchDataList();
                                }
                              });
                            },
                          ),
                        ),
                        Offstage(
                            offstage: statusInfo["openFlag"] == false,
                            child: StatusBtn(
                              margin: EdgeInsets.only(left: 10.px),
                              height: 28.px,
                              width: 68.px,
                              color: WColors.border,
                              fontColor: WColors.mainTextColor,
                              text: "取消",
                              isItemBtn: true,
                              onPressed: () {
                                RouteHelper.pushWidget(context,
                                        BookCancelPage(bookId: item["id"]))
                                    .then((isCancel) {
                                  if (isCancel != null && isCancel) {
                                    fetchDataList();
                                    setState(() {});
                                  }
                                });
                              },
                            ))
                      ],
                    ),
                  )
                ])));
  }

  Widget ItemInfoRow(title, content) {
    //设置内容默认样式
    TextStyle textStyle = TextStyle(
      fontSize: WDimens.tsMedium,
      color: WColors.mainTextColor, // 默认文本颜色
    );

    if (content == "先生" || content == "女士") {
      textStyle = textStyle.copyWith(
          fontSize: WDimens.tsMedium, fontWeight: FontWeight.bold);
    }
    return Container(
      margin: EdgeInsets.only(bottom: 5.px, left: 10.px),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          WText(
            title,
            style: TextStyle(
                fontSize: WDimens.tsMedium, color: WColors.subTextColor),
          ),
          SizedBox(
            width: 10.px,
          ),
          WText(
            content,
            style: textStyle,
          ),
        ],
      ),
    );
  }

  Widget ItemSingleInfoRow(content) {
    //设置内容默认样式
    TextStyle textStyle = TextStyle(
      fontSize: WDimens.tsMedium,
      color: WColors.mainTextColor, // 默认文本颜色
    );
    return Container(
      margin: EdgeInsets.only(bottom: 5.px, left: 10.px),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          WText(
            content,
            style: textStyle,
          ),
        ],
      ),
    );
  }
}
